
#> pip3 install pymodbus==2.5.3
from pymodbus.client.sync import ModbusSerialClient

# 连接 Modbus RTU 设备
client = ModbusSerialClient(method='rtu', port='/dev/ttyUSB3', baudrate=38400)
client.connect()

# 读取一个保持寄存器
result = client.read_holding_registers(address=0, count=100, unit=2)

# 处理读取结果
if result.isError():
    print( "Modbus error :" , len(result))
else:
    value = result.registers[0]
    print(f"Register value: {value}")
    s = len(result.registers)
    for i in range(s):
        v = result.registers[i]
        print(f"Register value[{i}]: {v}")


# 关闭 Modbus 连接
client.close()